import collectApi from '../../api/collectApi'
const app = getApp()
Component({

    /**
     * 组件的属性列表
     */
    properties: {
      activeId: String
    },

    /**
     * 组件的初始数据
     */
    data: {
      isCollected: false
    },

    observers: {
      activeId: function(value) {
        
        this.mounted()
      }
    },

    lifetimes: {
      // 生命周期函数，可以为函数，或一个在methods段中定义的方法名
      attached: function(){
        
      },
      moved: function () { },
      detached: function () { },
    },
    
    pageLifetimes: {
      // 组件所在页面的生命周期函数
      show: function () { },
      hide: function () { },
      resize: function () { },
    },

    /**
     * 组件的方法列表
     */
    methods: {
      async mounted(){
        
        if(!this.data.activeId){
          return
        }
        await app.getOpenid()
        let res = await collectApi.getList({
          pageNum:1,
          pageSize: 1,
          activeId: this.data.activeId,
          openid: wx.getStorageSync('openid')
        })
        this.setData({
          isCollected: res.length > 0
        })
      },
      async collect(){
        wx.showLoading({
          mask:true
        })
        if(this.data.isCollected){
          await collectApi.delete({
            openid: wx.getStorageSync('openid'),
            activeId: this.data.activeId,
          })
        } else {
          await collectApi.add({
            openid: wx.getStorageSync('openid'),
            activeId: this.data.activeId,
          })
        }
        wx.hideLoading( )
        this.setData({
          isCollected: !this.data.isCollected
        })
      },
      toComment(){
        wx.navigateTo({
          url: '/comment/addComment/addComment?activeId=' + this.data.activeId,
        })
      }
    }
})